// GuideMask.ts
import { _decorator, Component, Graphics, director, Color, Vec3, Node, Mask, math } from 'cc';
import { GuideEvent } from './GuideEvent';
const { ccclass } = _decorator;

@ccclass('GuideMask')
export class GuideMask extends Component {
    private graphics: Graphics = null!;

    onLoad() {
        this.graphics = this.getComponent(Graphics)!;
        if (!this.graphics) {
            console.error("Graphics 组件未找到");
            return;
        }
        this.graphics.enabled = true; // 确保组件启用

        // 监听事件
        director.on(GuideEvent.SHOW_MASK, this.show, this);
        // director.on(GuideEvent.HIDE_MASK, this.hide, this);
    }
    protected start(): void {
        // console.log('开始')
        // // 红色矩形
        // const ctx = this.node.getComponent(Graphics);
        // ctx.lineWidth = 6;
        // ctx.strokeColor = Color.RED;
        // ctx.rect(0,0, 290, 140);
        // ctx.fill();
    }

    onDestroy() {
        // 取消监听
        director.off(GuideEvent.SHOW_MASK, this.show, this);
        director.off(GuideEvent.HIDE_MASK, this.hide, this);
    }

    private show(targetNode: Node, shape: string) {
        const worldPos = targetNode.getWorldPosition();
        console.log("目标节点世界坐标:", worldPos);
        this.drawHole(worldPos, shape);

    }

    private hide() {
        this.graphics.clear();
    }

    private drawHole(pos: Vec3, shape: string) {


        console.log('绘制了');
        const ctx = this.node.getComponent(Graphics);
        if(!ctx){
            console.log('节点不存在')
        }
        console.log("绘制遮罩，位置:", pos, "形状:", shape);
        this.graphics.clear();
        this.graphics.fillColor = new Color(0, 0, 0, 180); // 半透明黑色
        this.graphics.rect(0, 0, screen.width, screen.height); // 全屏遮罩
        this.graphics.fill();
        if (shape === 'circle') {
            this.graphics.circle(Math.floor(pos.x),Math.floor( pos.y), 50); // 圆形高亮
        } else {
            this.graphics.rect(Math.floor(pos.x)- 100, Math.floor( pos.y)- 50, 200, 100); // 矩形高亮
        }
        this.graphics.fill();

        // 将节点移动到屏幕左下角
        this.node.setPosition(-screen.width / 2, -screen.height / 2);
    }
}